package com.xjrsoft.module.erpModel.caseErpCustomer.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.YesOrNoEnum;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.RedisUtil;
import com.xjrsoft.module.erpModel.caseErpCustomer.dto.*;
import com.xjrsoft.module.erpModel.caseErpCustomer.entity.*;
import com.xjrsoft.module.erpModel.caseErpCustomer.mapper.CaseErpCustomerGatherDetailMapper;
import com.xjrsoft.module.erpModel.caseErpCustomer.mapper.CaseErpCustomerGatherMapper;
import com.xjrsoft.module.erpModel.caseErpCustomer.mapper.CaseErpCustomerMapper;
import com.xjrsoft.module.erpModel.caseErpCustomer.service.*;
import com.xjrsoft.module.erpModel.caseErpCustomer.vo.*;
import com.xjrsoft.module.erpModel.caseErpLog.entity.CaseErpLog;
import com.xjrsoft.module.erpModel.caseErpLog.service.ICaseErpLogService;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.system.entity.DictionaryDetail;
import com.xjrsoft.module.system.service.IDictionarydetailService;
import com.xjrsoft.module.workflow.utils.WorkFlowUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 客户信息【case_erp_customer】 服务实现类
 * </p>
 *
 * @author hnyyzy
 * @since 2023-07-11
 */
@Service
@AllArgsConstructor
public class CaseErpCustomerServiceImpl extends MPJBaseServiceImpl<CaseErpCustomerMapper, CaseErpCustomer> implements ICaseErpCustomerService {

    private final ICaseErpCustomerContactsService caseErpCustomerContactsService;

    private final ICaseErpCustomerFollowService caseErpCustomerFollowService;

    private final CaseErpCustomerGatherDetailMapper caseErpCustomerGatherDetailMapper;

    private final CaseErpCustomerGatherMapper caseErpCustomerGatherMapper;


    private final IDictionarydetailService dictionarydetailService;

    private RedisUtil redisUtil;

    private ICaseErpLogService caseErpLogService;

    @Override
    public PageOutput<CaseErpCustomerVo> getPageList(CaseErpCustomerDto dto) {
        if (ObjectUtil.isNotNull(dto.getStartTime()) && ObjectUtil.isNotNull(dto.getEndTime())) {
            dto.setStartTime(WorkFlowUtil.getStartOfDay(dto.getStartTime()));
            dto.setEndTime(WorkFlowUtil.getEndOfDay(dto.getEndTime()));
        }

        List<CaseErpCustomer> list = this.list(Wrappers.lambdaQuery(CaseErpCustomer.class)
                        .orderByDesc(CaseErpCustomer::getCreateDate)
                .eq(ObjectUtil.isNotEmpty(dto.getState()), CaseErpCustomer::getState, dto.getState())
                .eq(ObjectUtil.isNotEmpty(dto.getTypeId()), CaseErpCustomer::getTypeId, dto.getTypeId())
                .like(StrUtil.isNotBlank(dto.getName()), CaseErpCustomer::getName, dto.getName())
                .like(ObjectUtil.isNotEmpty(dto.getState()) && dto.getState().equals(YesOrNoEnum.NO.getCode()),
                        CaseErpCustomer::getSaleIds, StpUtil.getLoginIdAsString()) // 当前人员的id,非公海客户
                .eq(ObjectUtil.isNotEmpty(dto.getSourceId()), CaseErpCustomer::getSourceId, dto.getSourceId())
                .between(ObjectUtil.isNotNull(dto.getStartTime()) && ObjectUtil.isNotNull(dto.getEndTime())
                        , CaseErpCustomer::getCreateDate, dto.getStartTime(), dto.getEndTime()));

        //进行id和名称的转换
        List<CaseErpCustomerVo> result = this.convert(list);
        PageOutput<CaseErpCustomerVo> output = new PageOutput<>();
        output.setCurrentPage(dto.getLimit());
        output.setPageSize(dto.getSize());
        output.setTotal(list.size());
        output.setList(result);

        return output;
    }

    @Override
    public Boolean common(List<Long> ids) {
        List<CaseErpCustomer> caseErpCustomerList = new ArrayList<>();
        List<CaseErpLog> caseErpLogList = new ArrayList<>();
        List<CaseErpCustomer> caseErpCustomers = this.list();
        for (Long id : ids) {
            //需要先查询再修改，防止出现转移的时候默认联系人、电话等数据为空，因为实体类设置了，更新时不忽略为空的数据    @TableField(updateStrategy = FieldStrategy.IGNORED)
            CaseErpCustomer caseErpCustomer = caseErpCustomers.stream().filter(x -> x.getId().equals(id)).findFirst().orElse(new CaseErpCustomer());
            if (caseErpCustomer == null){
                throw new MyException("找不到此客户信息！");
            }
            caseErpCustomer.setState(YesOrNoEnum.YES.getCode());
            caseErpCustomer.setSaleIds(null);
            caseErpCustomer.setInOpenDate(LocalDateTime.now());
            caseErpCustomerList.add(caseErpCustomer);

            CaseErpLog log = new CaseErpLog();
            log.setKeyId(id);
            log.setCategoryId(0);
            log.setExecuteResultJson("客户移入公海");
            caseErpLogList.add(log);
        }
        this.updateBatchById(caseErpCustomerList);
        caseErpLogService.saveBatch(caseErpLogList);
        return true;
    }

    @Override
    public Boolean transfer(TransferCaseErpCustomerDto dto) {
        //需要先查询再修改，防止出现转移的时候默认联系人、电话等数据为空，因为实体类设置了，更新时不忽略为空的数据    @TableField(updateStrategy = FieldStrategy.IGNORED)
        CaseErpCustomer caseErpCustomer = this.getById(dto.getId());
        if (caseErpCustomer == null){
            throw new MyException("找不到此客户信息！");
        }
        caseErpCustomer.setId(dto.getId());
        caseErpCustomer.setSaleIds(dto.getSaleIds());
        this.updateById(caseErpCustomer);

        CaseErpLog log = new CaseErpLog();
        log.setKeyId(dto.getId());
        log.setCategoryId(0);
        log.setExecuteResultJson("客户转移");
        caseErpLogService.save(log);

        return true;
    }

    @Override
    public CaseErpCustomerInfoVo info(CaseErpCustomer caseErpCustomer) {
        CaseErpCustomerInfoVo caseErpCustomerInfoVo = BeanUtil.toBean(caseErpCustomer, CaseErpCustomerInfoVo.class);
        List<CaseErpCustomerContacts> list = caseErpCustomerContactsService.list(Wrappers.<CaseErpCustomerContacts>query().lambda().eq(CaseErpCustomerContacts::getCustomerId, caseErpCustomer.getId()));
        caseErpCustomerInfoVo.setCaseErpCustomerContacts(list);
        return caseErpCustomerInfoVo;
    }

    @Override
    public List<CaseErpCustomerExportVo> export(List<Long> ids) {
        List<CaseErpCustomer> list = this.list(Wrappers.lambdaQuery(CaseErpCustomer.class)
                .in(CaseErpCustomer::getId, ids));
        //进行id和名称的转换
        List<CaseErpCustomerVo> result = this.convert(list);
        List<CaseErpCustomerExportVo> exportVoList = BeanUtil.copyToList(result, CaseErpCustomerExportVo.class);
        return exportVoList;
    }

    @Override
    public Boolean importData(MultipartFile file) throws IOException {
        return this.importCommon(file, YesOrNoEnum.NO.getCode());
    }

    /**
     * 客户列表与公海列表导入公共方法
     *
     * @param file  导入的文件
     * @param state 1公海列表，0客户列表
     * @return
     * @throws IOException
     */
    private Boolean importCommon(MultipartFile file, Integer state) throws IOException {
        List<ImportCaseErpCustomerDto> savedDataList = EasyExcel.read(file.getInputStream()).head(ImportCaseErpCustomerDto.class).sheet().doReadSync();
        List<CaseErpCustomer> caseErpCustomerList = new ArrayList<>();
        List<DictionaryDetail> dictionaryDetailList = dictionarydetailService.list();
        for (ImportCaseErpCustomerDto importCaseErpCustomerDto : savedDataList) {
            CaseErpCustomer caseErpCustomer = BeanUtil.toBean(importCaseErpCustomerDto, CaseErpCustomer.class);
            if (state == YesOrNoEnum.NO.getCode()) {
                caseErpCustomer.setState(YesOrNoEnum.NO.getCode());
                caseErpCustomer.setSaleIds(StpUtil.getLoginIdAsString());
            } else {
                caseErpCustomer.setState(YesOrNoEnum.YES.getCode());
                caseErpCustomer.setSaleIds(null);
            }
            if (StrUtil.isNotBlank(importCaseErpCustomerDto.getTypeName())) {
                DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getName().equals(importCaseErpCustomerDto.getTypeName())).findFirst().orElse(new DictionaryDetail());
                if (ObjectUtil.isNotEmpty(dictionaryDetail.getId())) {
                    caseErpCustomer.setTypeId(dictionaryDetail.getId());
                }
            }
            if (StrUtil.isNotBlank(importCaseErpCustomerDto.getScaleName())) {
                DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getName().equals(importCaseErpCustomerDto.getScaleName())).findFirst().orElse(new DictionaryDetail());
                if (ObjectUtil.isNotEmpty(dictionaryDetail.getId())) {
                    caseErpCustomer.setScaleId(dictionaryDetail.getId());
                }
            }
            if (StrUtil.isNotBlank(importCaseErpCustomerDto.getNatureName())) {
                DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getName().equals(importCaseErpCustomerDto.getNatureName())).findFirst().orElse(new DictionaryDetail());
                if (ObjectUtil.isNotEmpty(dictionaryDetail.getId())) {
                    caseErpCustomer.setNatureId(dictionaryDetail.getId());
                }
            }
            if (StrUtil.isNotBlank(importCaseErpCustomerDto.getSourceName())) {
                DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getName().equals(importCaseErpCustomerDto.getSourceName())).findFirst().orElse(new DictionaryDetail());
                if (ObjectUtil.isNotEmpty(dictionaryDetail.getId())) {
                    caseErpCustomer.setSourceId(dictionaryDetail.getId());
                }
            }
            caseErpCustomerList.add(caseErpCustomer);
        }
        return this.saveBatch(BeanUtil.copyToList(caseErpCustomerList, CaseErpCustomer.class));
    }

    @Override
    public List<CaseErpCustomerCommonExportVo> exportCommon() {
        List<CaseErpCustomer> list = this.list(Wrappers.lambdaQuery(CaseErpCustomer.class)
                .in(CaseErpCustomer::getState, YesOrNoEnum.YES.getCode()));
        //进行id和名称的转换
        List<CaseErpCustomerVo> result = this.convert(list);
        List<CaseErpCustomerCommonExportVo> exportVoList = BeanUtil.copyToList(result, CaseErpCustomerCommonExportVo.class);
        return exportVoList;
    }

    @Override
    public Boolean importCommonData(MultipartFile file) throws IOException {
        return this.importCommon(file, YesOrNoEnum.YES.getCode());
    }

    @Override
    public CaseErpCustomerVo baseInfo(CaseErpCustomer caseErpCustomer) {
        List<CaseErpCustomer> caseErpCustomerList = new ArrayList<>();
        caseErpCustomerList.add(caseErpCustomer);
        //做转换使用
        List<CaseErpCustomerVo> convert = this.convert(caseErpCustomerList);
        CaseErpCustomerVo caseErpCustomerVo = new CaseErpCustomerVo();
        if (CollectionUtil.isNotEmpty(convert)) {
            caseErpCustomerVo = convert.get(0);
        }
        return caseErpCustomerVo;
    }

    @Override
    public CaseErpCustomerDetailInfoVo detailInfo(CaseErpCustomer caseErpCustomer) {
        List<DictionaryDetail> dictionaryDetailList = dictionarydetailService.list();
        List<User> userList = redisUtil.get(GlobalConstant.USER_CACHE_KEY, new TypeReference<List<User>>() {
        });
        CaseErpCustomerDetailInfoVo caseErpCustomerDetailInfoVo = new CaseErpCustomerDetailInfoVo();
        //客户信息
        CaseErpCustomerVo caseErpCustomerVo = this.baseInfo(caseErpCustomer);
        caseErpCustomerDetailInfoVo.setId(caseErpCustomer.getId());
        caseErpCustomerDetailInfoVo.setCaseErpCustomerVo(caseErpCustomerVo);
        //跟进人信息
        List<CaseErpCustomerFollow> list = caseErpCustomerFollowService.list(Wrappers.<CaseErpCustomerFollow>query().lambda()
                .eq(CaseErpCustomerFollow::getCustomerId, caseErpCustomer.getId()).orderByDesc(CaseErpCustomerFollow::getCreateDate));
        List<CaseErpCustomerFollowInfoVo> caseErpCustomerFollowInfoVoList = caseErpCustomerFollowService.info(list, dictionaryDetailList, userList);
        caseErpCustomerDetailInfoVo.setCaseErpCustomerFollowInfoVoList(caseErpCustomerFollowInfoVoList);
        //联系人信息
        List<CaseErpCustomerContacts> caseErpCustomerContactsList = caseErpCustomerContactsService.list(Wrappers.<CaseErpCustomerContacts>query().lambda()
                .eq(CaseErpCustomerContacts::getCustomerId, caseErpCustomer.getId()).orderByDesc(CaseErpCustomerContacts::getCreateDate));
        List<CaseErpCustomerContactsInfoVo> caseErpCustomerContactsInfoVoList = caseErpCustomerContactsService.info(caseErpCustomerContactsList, userList);
        caseErpCustomerDetailInfoVo.setCaseErpCustomerContactsInfoVoList(caseErpCustomerContactsInfoVoList);
        //操作记录
        List<CaseErpLog> caseErpLogList = caseErpLogService.list(Wrappers.<CaseErpLog>query().lambda()
                .eq(CaseErpLog::getKeyId, caseErpCustomer.getId()).orderByDesc(CaseErpLog::getCreateDate));

        for (CaseErpLog caseErpLog : caseErpLogList) {
            if (ObjectUtil.isNotEmpty(caseErpLog.getCreateUserId())){
                User user = userList.stream().filter(x -> x.getId().equals(caseErpLog.getCreateUserId())).findFirst().orElse(new User());
                caseErpLog.setOperateUserAccount(user.getName());
            }
        }
        caseErpCustomerDetailInfoVo.setCaseErpLogList(caseErpLogList);

        return caseErpCustomerDetailInfoVo;
    }

    @Override
    public Boolean getFromCommon(Long id) {
        //需要先查询再修改，防止出现转移的时候默认联系人、电话等数据为空，因为实体类设置了，更新时不忽略为空的数据    @TableField(updateStrategy = FieldStrategy.IGNORED)
        CaseErpCustomer customer = this.getById(id);
        customer.setState(YesOrNoEnum.NO.getCode());
        customer.setSaleIds(StpUtil.getLoginIdAsString());
        this.updateById(customer);

        CaseErpLog log = new CaseErpLog();
        log.setKeyId(id);
        log.setCategoryId(0);
        log.setExecuteResultJson("客户领取");
        caseErpLogService.save(log);

        return true;
    }

    @Override
    public List<CustomerSourceVo> getCustomerSource() {
        List<CustomerSourceVo> list = new ArrayList<>();
        CustomerSourceVo supplierRiskVo = new CustomerSourceVo();
        supplierRiskVo.setName("访问官网");
        supplierRiskVo.setValue(25);
        CustomerSourceVo supplierRiskVo2 = new CustomerSourceVo();
        supplierRiskVo2.setName("电话销售");
        supplierRiskVo2.setValue(35);
        CustomerSourceVo supplierRiskVo3 = new CustomerSourceVo();
        supplierRiskVo3.setName("客户介绍");
        supplierRiskVo3.setValue(20);
        CustomerSourceVo supplierRiskVo4 = new CustomerSourceVo();
        supplierRiskVo4.setName("主动来电");
        supplierRiskVo4.setValue(18);
        CustomerSourceVo supplierRiskVo5 = new CustomerSourceVo();
        supplierRiskVo5.setName("其他途径");
        supplierRiskVo5.setValue(2);
        list.add(supplierRiskVo);
        list.add(supplierRiskVo2);
        list.add(supplierRiskVo3);
        list.add(supplierRiskVo4);
        list.add(supplierRiskVo5);
        return list;
    }

    @Override
    public List<CustomerAllVo> getAll() {
        List<CustomerAllVo> result = new ArrayList<>();

        List<CaseErpCustomer> caseErpCustomerList = this.baseMapper.selectList(Wrappers.<CaseErpCustomer>query().lambda()
                .eq(CaseErpCustomer::getState,0)
                .gt(CaseErpCustomer::getCreateDate,DateUtil.offset(DateUtil.parse(DateUtil.now(),"yyyy-MM-dd"), DateField.DAY_OF_MONTH,-1))
                .lt(CaseErpCustomer::getCreateDate,DateUtil.offset(DateUtil.parse(DateUtil.now(),"yyyy-MM-dd"), DateField.DAY_OF_MONTH,-1))
        );
        CustomerAllVo customerAllVo = new CustomerAllVo();
        customerAllVo.setName("今日新增客户");
        customerAllVo.setNum(caseErpCustomerList.size());
        result.add(customerAllVo);

        List<CaseErpCustomerFollow> caseErpCustomerFollowList = caseErpCustomerFollowService.list(Wrappers.<CaseErpCustomerFollow>query().lambda()
                        .gt(CaseErpCustomerFollow::getCreateDate,DateUtil.offset(DateUtil.parse(DateUtil.now(),"yyyy-MM-dd"), DateField.DAY_OF_MONTH,-1))
                        .lt(CaseErpCustomerFollow::getCreateDate,DateUtil.offset(DateUtil.parse(DateUtil.now(),"yyyy-MM-dd"), DateField.DAY_OF_MONTH,-1))
                );
        CustomerAllVo customerAllVo2 = new CustomerAllVo();
        customerAllVo2.setName("今日跟进客户");
        customerAllVo2.setNum(caseErpCustomerFollowList.size());
        result.add(customerAllVo2);

        List<CaseErpCustomerGatherDetail> caseErpCustomergatherdetails = caseErpCustomerGatherDetailMapper.selectList(Wrappers.<CaseErpCustomerGatherDetail>query().lambda()
                .gt(CaseErpCustomerGatherDetail::getRefundDate,DateUtil.offset(DateUtil.parse(DateUtil.now(),"yyyy-MM-dd"), DateField.DAY_OF_MONTH,-1))
                .lt(CaseErpCustomerGatherDetail::getRefundDate,DateUtil.offset(DateUtil.parse(DateUtil.now(),"yyyy-MM-dd"), DateField.DAY_OF_MONTH,1)));
        CustomerAllVo customerAllVo3=new CustomerAllVo();
        customerAllVo3.setName("今日回款客户");
        customerAllVo3.setNum(caseErpCustomergatherdetails.size());
        result.add(customerAllVo3);


        List<CaseErpCustomerFollow> caseErpCustomerfollows2 = caseErpCustomerFollowService.list(Wrappers.<CaseErpCustomerFollow>query().lambda()
                .gt(CaseErpCustomerFollow::getNextFollowTime,DateUtil.offset(DateUtil.parse(DateUtil.now(),"yyyy-MM-dd"), DateField.DAY_OF_MONTH,0))
        );
        CustomerAllVo customerAllVo4=new CustomerAllVo();
        customerAllVo4.setName("待跟进客户");
        customerAllVo4.setNum(caseErpCustomerfollows2.size());
        result.add(customerAllVo4);

        List<CaseErpCustomerGather> caseErpCustomergathers = caseErpCustomerGatherMapper.selectList(Wrappers.<CaseErpCustomerGather>query().lambda()
                .gt(CaseErpCustomerGather::getReceivedDate, DateUtil.offset(DateUtil.parse(DateUtil.now(),"yyyy-MM-dd"), DateField.MONTH,0)));
        CustomerAllVo customerAllVo5=new CustomerAllVo();
        customerAllVo5.setName("待回款客户");
        customerAllVo5.setNum(caseErpCustomergathers.size());
        result.add(customerAllVo5);

        return result;
    }

    @Override
    public List<CustomerPxaymentVo> getCustomerPaymexnt() {
        List<CustomerPxaymentVo>list=new ArrayList<>();
        CustomerPxaymentVo vo=new CustomerPxaymentVo();
        List<String>category=new ArrayList<>();
        List<Integer>data=new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            category.add(i+1+"月"); data.add(77+i*15);
        }
        vo.setCategory(category);vo.setData(data);vo.setKey(2);vo.setName("年度");list.add(vo);
        CustomerPxaymentVo vo2=new CustomerPxaymentVo();
        List<String>category2=new ArrayList<>();
        List<Integer>data2=new ArrayList<>();
        category2.add("一季度"); category2.add("二季度"); category2.add("三季度"); category2.add("四季度");
        data2.add(100);data2.add(235);data2.add(300);data2.add(365);
        vo2.setCategory(category2);vo2.setData(data2);vo2.setKey(1);vo2.setName("季度");list.add(vo2);
        CustomerPxaymentVo vo3=new CustomerPxaymentVo();
        List<String>category3=new ArrayList<>();
        List<Integer>data3=new ArrayList<>();
        for (int i = 0; i < 30; i++) {
            category3.add(i+1+"日"); data3.add(57+i*11);
        }
        vo3.setCategory(category3);vo3.setData(data3);vo3.setKey(0);vo3.setName("月度");list.add(vo3);
        return list;
    }

    @Override
    public List<CustomerVo> getCustomerType() {
        List<CustomerVo> result = new ArrayList<>();
        List<CaseErpCustomer> caseErpCustomerList = this.list();
        List<DictionaryDetail> list = dictionarydetailService.list(Wrappers.<DictionaryDetail>query().lambda().eq(DictionaryDetail::getItemId, 1679007059387240450L));
        for (DictionaryDetail dictionaryDetail : list) {
            CustomerVo customerVo = new CustomerVo();
            customerVo.setName(dictionaryDetail.getName());
            List<CaseErpCustomer> collect = caseErpCustomerList.stream().filter(x -> x.getTypeId().equals(dictionaryDetail.getId())).collect(Collectors.toList());
            customerVo.setValue(collect.size());
            result.add(customerVo);
        }
        return result;
    }

    /**
     * 将id转换成名称
     *
     * @param list
     * @return
     */
    private List<CaseErpCustomerVo> convert(List<CaseErpCustomer> list) {
        List<CaseErpCustomerVo> result = new ArrayList<>();
        List<DictionaryDetail> dictionaryDetailList = dictionarydetailService.list();
        List<User> userList = redisUtil.get(GlobalConstant.USER_CACHE_KEY, new TypeReference<List<User>>() {
        });
        for (CaseErpCustomer caseErpCustomer : list) {
            CaseErpCustomerVo caseErpCustomerVo = BeanUtil.toBean(caseErpCustomer, CaseErpCustomerVo.class);
            if (ObjectUtil.isNotEmpty(caseErpCustomer.getTypeId())) {
                DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getId().equals(caseErpCustomer.getTypeId())).findFirst().orElse(new DictionaryDetail());
                if (StrUtil.isNotBlank(dictionaryDetail.getName())) {
                    caseErpCustomerVo.setTypeName(dictionaryDetail.getName());
                }
            }
            if (ObjectUtil.isNotEmpty(caseErpCustomer.getSourceId())) {
                DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getId().equals(caseErpCustomer.getSourceId())).findFirst().orElse(new DictionaryDetail());
                if (StrUtil.isNotBlank(dictionaryDetail.getName())) {
                    caseErpCustomerVo.setSourceName(dictionaryDetail.getName());
                }
            }
            if (ObjectUtil.isNotEmpty(caseErpCustomer.getNatureId())) {
                DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getId().equals(caseErpCustomer.getNatureId())).findFirst().orElse(new DictionaryDetail());
                if (StrUtil.isNotBlank(dictionaryDetail.getName())) {
                    caseErpCustomerVo.setNatureName(dictionaryDetail.getName());
                }
            }
            if (ObjectUtil.isNotEmpty(caseErpCustomer.getScaleId())) {
                DictionaryDetail dictionaryDetail = dictionaryDetailList.stream().filter(x -> x.getId().equals(caseErpCustomer.getScaleId())).findFirst().orElse(new DictionaryDetail());
                if (StrUtil.isNotBlank(dictionaryDetail.getName())) {
                    caseErpCustomerVo.setScaleName(dictionaryDetail.getName());
                }
            }
            if (ObjectUtil.isNotEmpty(caseErpCustomer.getSaleIds())) {
                List<Long> userIds = userList.stream().filter(x -> caseErpCustomer.getSaleIds().contains(x.getId().toString())).map(User::getId).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(userIds)) {
                    String userNames = WorkFlowUtil.getAllUserNamesByIds(userIds);
                    caseErpCustomerVo.setSaleName(userNames);
                }
            }
            if (ObjectUtil.isNotEmpty(caseErpCustomer.getCreateUserId())) {
                User user = userList.stream().filter(x -> x.getId().equals(caseErpCustomer.getCreateUserId())).findFirst().orElse(new User());
                if (StrUtil.isNotBlank(user.getName())) {
                    caseErpCustomerVo.setCreateUserName(user.getName());
                }
            }
            result.add(caseErpCustomerVo);
        }
        return result;
    }

    @Override
    public Boolean add(AddCaseErpCustomerDto dto) {
        CaseErpCustomer caseErpCustomer = BeanUtil.toBean(dto, CaseErpCustomer.class);
        if (ObjectUtil.isNotEmpty(dto.getState()) && dto.getState() == YesOrNoEnum.NO.getCode()) {
            caseErpCustomer.setSaleIds(StpUtil.getLoginIdAsString());//正常新增
        } else {//公海新增
            caseErpCustomer.setInOpenDate(LocalDateTime.now());
        }
        boolean save = this.save(caseErpCustomer);
        if (CollectionUtil.isNotEmpty(dto.getAddCaseErpCustomerContactsDtoList())) {
            CaseErpCustomerContactsDto caseErpCustomerContactsDto1 = dto.getAddCaseErpCustomerContactsDtoList().stream().filter(x -> x.getIsDefault().equals(YesOrNoEnum.YES.getCode())).findFirst().orElse(new CaseErpCustomerContactsDto());
            if (StrUtil.isNotBlank(caseErpCustomerContactsDto1.getName())) {
                caseErpCustomer.setDefaultName(caseErpCustomerContactsDto1.getName());
            }
            if (StrUtil.isNotBlank(caseErpCustomerContactsDto1.getPhone())) {
                caseErpCustomer.setDefaultPhone(caseErpCustomerContactsDto1.getPhone());
            }
            if (StrUtil.isNotBlank(caseErpCustomerContactsDto1.getDept())) {
                caseErpCustomer.setDefaultDep(caseErpCustomerContactsDto1.getDept());
            }
            if (StrUtil.isNotBlank(caseErpCustomerContactsDto1.getPost())) {
                caseErpCustomer.setDefaultPost(caseErpCustomerContactsDto1.getPost());
            }
            this.updateById(caseErpCustomer);
            List<CaseErpCustomerContacts> caseErpCustomerContacts = BeanUtil.copyToList(dto.getAddCaseErpCustomerContactsDtoList(), CaseErpCustomerContacts.class);
            if (save && CollectionUtil.isNotEmpty(caseErpCustomerContacts)) {
                for (CaseErpCustomerContacts caseErpCustomerContact : caseErpCustomerContacts) {
                    caseErpCustomerContact.setCustomerId(caseErpCustomer.getId());
                }
                caseErpCustomerContactsService.saveBatch(caseErpCustomerContacts);
            }
        }
        if (dto.getState() == YesOrNoEnum.YES.getCode()) {//公海客户新增
            CaseErpLog log = new CaseErpLog();
            log.setKeyId(caseErpCustomer.getId());
            log.setCategoryId(0);
            log.setExecuteResultJson("新增公海客户信息");
            caseErpLogService.save(log);
        } else {//客户新增
            CaseErpLog log = new CaseErpLog();
            log.setKeyId(caseErpCustomer.getId());
            log.setCategoryId(0);
            log.setExecuteResultJson("新增客户信息");
            caseErpLogService.save(log);
        }
        return true;
    }

    @Override
    public Boolean update(UpdateCaseErpCustomerDto dto) {
        CaseErpCustomer caseErpCustomer = BeanUtil.toBean(dto, CaseErpCustomer.class);
        boolean save = this.updateById(caseErpCustomer);
        if (CollectionUtil.isNotEmpty(dto.getAddCaseErpCustomerContactsDtoList())) {
            CaseErpCustomerContactsDto caseErpCustomerContactsDto1 = dto.getAddCaseErpCustomerContactsDtoList().stream().filter(x -> x.getIsDefault().equals(YesOrNoEnum.YES.getCode())).findFirst().orElse(new CaseErpCustomerContactsDto());
            if (StrUtil.isNotBlank(caseErpCustomerContactsDto1.getName())) {
                caseErpCustomer.setDefaultName(caseErpCustomerContactsDto1.getName());
            }
            if (StrUtil.isNotBlank(caseErpCustomerContactsDto1.getPhone())) {
                caseErpCustomer.setDefaultPhone(caseErpCustomerContactsDto1.getPhone());
            }
            if (StrUtil.isNotBlank(caseErpCustomerContactsDto1.getDept())) {
                caseErpCustomer.setDefaultDep(caseErpCustomerContactsDto1.getDept());
            }
            if (StrUtil.isNotBlank(caseErpCustomerContactsDto1.getPost())) {
                caseErpCustomer.setDefaultPost(caseErpCustomerContactsDto1.getPost());
            }
            this.updateById(caseErpCustomer);
            List<CaseErpCustomerContacts> caseErpCustomerContacts = BeanUtil.copyToList(dto.getAddCaseErpCustomerContactsDtoList(), CaseErpCustomerContacts.class);
            if (save) {
                for (CaseErpCustomerContacts caseErpCustomerContact : caseErpCustomerContacts) {
                    caseErpCustomerContact.setCustomerId(caseErpCustomer.getId());
                }
                //先删除再新增
                caseErpCustomerContactsService.remove(Wrappers.<CaseErpCustomerContacts>query().lambda().eq(CaseErpCustomerContacts::getCustomerId, caseErpCustomer.getId()));
                caseErpCustomerContactsService.saveBatch(caseErpCustomerContacts);
            }
        }else {
            caseErpCustomer.setDefaultName(null);
            caseErpCustomer.setDefaultPhone(null);
            caseErpCustomer.setDefaultPost(null);
            caseErpCustomer.setDefaultDep(null);
            this.updateById(caseErpCustomer);
            caseErpCustomerContactsService.remove(Wrappers.<CaseErpCustomerContacts>query().lambda().eq(CaseErpCustomerContacts::getCustomerId, caseErpCustomer.getId()));
        }
        if (dto.getState() == YesOrNoEnum.YES.getCode()) {//公海客户修改
            CaseErpLog log = new CaseErpLog();
            log.setKeyId(caseErpCustomer.getId());
            log.setCategoryId(0);
            log.setExecuteResultJson("修改公海客户信息");
            caseErpLogService.save(log);
        } else {//客户新增
            CaseErpLog log = new CaseErpLog();
            log.setKeyId(caseErpCustomer.getId());
            log.setCategoryId(0);
            log.setExecuteResultJson("修改客户信息");
            caseErpLogService.save(log);
        }
        return true;
    }

    @Override
    public Boolean delete(Long id) {
        //删客户表信息
        this.removeById(id);
        //删除联系表信息
        caseErpCustomerContactsService.remove(Wrappers.<CaseErpCustomerContacts>query().lambda().eq(CaseErpCustomerContacts::getCustomerId, id));
        //删除跟进表数据
        caseErpCustomerFollowService.remove(Wrappers.<CaseErpCustomerFollow>query().lambda().eq(CaseErpCustomerFollow::getCustomerId, id));
        return true;
    }

}
